from Cryptodome.Cipher import AES
from Cryptodome import Random
from binascii import b2a_hex

# 要加密的明文
data = '南来北往'
#  密钥key 长度必须为16（AES-128）、24（AES-192）、或32（AES-256）Bytes 长度.
#  目前AES-128足够用
key = b'this is a 16 key'
#  生成长度等于AES块大小的不可重复的密钥向量
iv = Random.new().read(AES.block_size)
#  使用key和iv初始化AES对象, 使用MODE_CFB模式
mycipher = AES.new(key, AES.MODE_CFB, iv)
#  加密的明文长度必须为16的倍数，如果长度不为16的倍数，则需要补足为16的倍数
#  将iv（密钥向量）加到加密的密文开头，一起传输
ciphertext = iv + mycipher.encrypt(data.encode())
#  解密的话要用key和iv生成新的AES对象
mydecrypt = AES.new(key, AES.MODE_CFB, ciphertext[:16])
#  使用新生成的AES对象，将加密的密文解密
decrypttext = mydecrypt.decrypt(ciphertext[16:])
print('密钥k为：', key)
print('iv为：', b2a_hex(ciphertext)[:16])
print('加密后数据为：', b2a_hex(ciphertext)[16:])
print('解密后数据为：', decrypttext.decode())

import rsa
import binascii


# 使用网页中获得的n和e值，将明文加密
def rsa_encrypt(rsa_n, rsa_e, message):
    # 用n值和e值生成公钥
    key = rsa.PublicKey(rsa_n, rsa_e)
    # 用公钥把明文加密
    message = rsa.encrypt(message.encode(), key)
    # 转化成常用的可读性高的十六进制
    message = binascii.b2a_hex(message)
    # 将加密结果转化回字符串并返回
    return message.decode()


# RSA的公钥有两个值n和e，我们在网站中获得的公钥一般就是这样的两个值。
# n常常为长度为256的十六进制字符串# e常常为十六进制‘10001’
pubkey_n = '8d7e6949d411ce14d7d233d7160f5b2cc753930caba4d5ad24f923a505253b9c39b09a059732250e56c594d735077cfcb0c3508e9f544f101bdf7e97fe1b0d97f273468264b8b24caaa2a90cd9708a417c51cf8ba35444d37c514a0490441a773ccb121034f29748763c6c4f76eb0303559c57071fd89234d140c8bb965f9725'
pubkey_e = '10001'
# 需要将十六进制转换成十进制
rsa_n = int(pubkey_n, 16)
rsa_e = int(pubkey_e, 16)
# 要加密的明文
message = '南北今天很忙'
print("公钥n值长度：", len(pubkey_n))
print(rsa_encrypt(rsa_n, rsa_e, message))

import base64

s = 'hello,word!'
t = bytes(s, 'ascii')
print(t)
print(len(t))
b1 = base64.b64encode(t)  # base64编码，编码的字符串必须是二进制形式的
print("base64编码 = ", b1)
# b'aGVsbG8sd29yZCE='

b2 = base64.b64decode(b'aGVsbG8sd29yZCE=')  # base64解码
print("base64解码 = ", b2)
# b'hello,word!'
from hashlib import md5

m = md5()
m.update(b'a@eD')
print("md5编码 = ", m.hexdigest())
with open(r"F:\workspace\gitee\LearningSummary\安全\msg1.bin", 'rb') as m1:
    d1 = m1.read()
with open(r"F:\workspace\gitee\LearningSummary\安全\msg2.bin", 'rb') as m2:
    d2 = m2.read()
dm1 = md5()
dm1.update(d1)
dm2 = md5()
dm2.update(d2)
print(dm1.hexdigest())
print(dm2.hexdigest())

from hashlib import md5
from string import printable
from itertools import permutations
from time import time
from functools import reduce


def decrypt_md5(md5_value):
    if len(md5_value) != 32:
        print('error')
        return
    md5_value = md5_value.lower()
    a = (reduce(lambda x, y: x + y, item) for item in permutations(printable, 4) if
         md5(reduce(lambda x, y: x + y, item).encode()).hexdigest() == md5_value)
    return list(a)


md5_value = m.hexdigest()
start = time()
result = decrypt_md5(md5_value)
print(result)
# if result:
#     print('\n Success: ' + md5_value + '==>' + result)
print('Time used:', time() - start)
